package com.jackrain.nea.web.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.schema.Column;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.web.SearchCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.query.QueryUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestController
@Api(value = "SeachController", description = "关键字界面查询rest")
public class SeachController {

    @Reference(version = "1",group = "ad")
    private SearchCmd searchCmd1;

    @Reference(version = "2",group = "cp")
    private SearchCmd searchCmd2;

    @Reference(version = "3",group = "ps")
    private SearchCmd searchCmd3;

    @Reference(version = "4",group = "vp")
    private SearchCmd searchCmd4;

    private String service = "com.jackrain.nea.web.SearchCmd";


    @ApiOperation(value="关键字查询", notes="根据中文表名或英文名检索返回，有权限和不可用限制！")
    @RequestMapping(path = "/p/cs/SearchWords",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject getSearchWords(HttpServletRequest request,
                                     @RequestParam(value="words", required=true)String words){

        User user = (User) ShiroSessionUtil.getAttribute("user");
        QuerySessionImpl session = new QuerySessionImpl(request);
        TableManager tm = session.getTableManager();

        String tableId="ad_table";
        Table table;
        table= tm.getTable(tableId);

        String center  = table.getCategory().getSubSystem().getCenter();
        String[] gv = center.split(":");
        if(gv.length != 2){
            throw new NDSException("center is error");
        }
        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), service,gv[0],gv[1]);
        log.info("edas service->"+service+":"+gv[0]+":"+gv[1]);

        JSONObject result = ((SearchCmd) o).getSearchWords(user,words);
        return result;
    }

    @ApiOperation(value="模糊查询", notes="根据输入键模糊查询")
    @RequestMapping(path = "/p/cs/fuzzyquerybyak",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject fuzzyQueryByAK(HttpServletRequest request,
                                     @RequestParam(value="ak", required=true)String ak,
                                     @RequestParam(value="colid", required=false)int columnId,
                                     @RequestParam(value="colname", required=false)String columnName,
                                     @RequestParam(value="fixedcolumns", required=false)String fixedcolumns){

        User userWeb= (User)request.getSession().getAttribute("user");
        QuerySession qsession= QueryUtils.createQuerySession(userWeb);
        TableManager manager=qsession.getTableManager();

        Column column = null;
        if(columnId > 0){
            column = manager.getColumn(columnId);
        }else if(columnName != null && columnName.length() > 0){
            column = manager.getColumn(columnName);
            columnId = column.getId();
        }
        Table table = column.getReferenceTable();
        if(table == null){
            throw new NDSException("reference table is null");
        }

        String center  = table.getCategory().getSubSystem().getCenter();
        String[] gv = center.split(":");
        if(gv.length != 2){
            throw new NDSException("center is error");
        }
        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), service,gv[0],gv[1]);
        log.info("edas service->"+service+":"+gv[0]+":"+gv[1]);

        JSONObject result = ((SearchCmd) o).fuzzyQueryByAK(userWeb,ak,columnId,fixedcolumns);
//        //字段配置fuzzyDK
        JSONObject tableProps = table.getJSONProps();
        String s = tableProps==null?"":tableProps.getString("fuzzyDK");
        String[] fuzzyDK = null;
        log.info("fuzzyDK service->"+result.getJSONArray("data"));
        if(s != null && s.length() > 1){
            fuzzyDK = s.split(",");
            JSONArray ja = new JSONArray();
            JSONArray data = result.getJSONArray("data");
            for(int i=0; data!=null && i<data.size(); i++){
                JSONObject row = new JSONObject(true);
                for(int j=0; j<fuzzyDK.length; j++){
                    row.put(fuzzyDK[j],data.getJSONObject(i).getJSONObject(fuzzyDK[j]).getString("val"));
                }
                row.put("id",data.getJSONObject(i).getJSONObject("id").getString("val"));
                row.put("value",data.getJSONObject(i).getJSONObject("value").getString("val"));
                ja.add(row);
            }
            result.put("data",ja);
        }
        return result;
    }

    @ApiOperation(value="查询单表", notes="动态根据表配置查询语句")
    @RequestMapping(path = "/p/cs/querySingle",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject querySingle(HttpServletRequest request,
                                  @RequestParam(value="fields", required=true)String fields,
                                  @RequestParam(value="tablename", required=true)String tablename,
                                  @RequestParam(value="whereKeys", required=false)String whereKeys){

        User userWeb= (User)request.getSession().getAttribute("user");
        QuerySession qsession= QueryUtils.createQuerySession(userWeb);
        TableManager manager=qsession.getTableManager();

        Table table = manager.getTable(tablename);
        if(table == null){
            throw new NDSException("table is null");
        }

        String center  = table.getCategory().getSubSystem().getCenter();
        String[] gv = center.split(":");
        if(gv.length != 2){
            throw new NDSException("center is error");
        }
        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), service,gv[0],gv[1]);
        log.info("edas service->"+service+":"+gv[0]+":"+gv[1]);

        JSONObject result = ((SearchCmd) o).querySingle(userWeb,fields,tablename,JSONObject.parseObject(whereKeys));
        return result;
    }

}
